package com.vr.xxaiagent.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * HTTP AI 调用
 *
 * @author hzh
 * @date 2025/05/30
 */
public class HttpAiInvoke {
    public static void main(String[] args) {
        // 1. 准备请求参数
        // 替换为你的DASHSCOPE_API_KEY[1](@ref)
        String apiKey = TestApi.API_KEY;
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

        // 2. 构建JSON请求体
        JSONObject requestBody = new JSONObject();
        requestBody.set("model", "qwen-plus");

        JSONObject input = new JSONObject();
        JSONArray messages = new JSONArray();
        messages.add(JSONUtil.createObj().set("role", "system").set("content", "You are a helpful assistant."));
        messages.add(JSONUtil.createObj().set("role", "user").set("content", "你是谁？"));

        input.set("messages", messages);
        requestBody.set("input", input);

        JSONObject parameters = new JSONObject();
        parameters.set("result_format", "message");
        requestBody.set("parameters", parameters);

        try {
            // 3. 发送HTTP请求[5,7](@ref)
            HttpResponse response = HttpRequest.post(url)
                    // 认证头[1](@ref)
                    .header("Authorization", "Bearer " + apiKey)
                    // 内容类型头
                    .header("Content-Type", "application/json")
                    // JSON请求体
                    .body(requestBody.toString())
                    // 20秒超时
                    .timeout(20000)
                    .execute();

            // 4. 处理响应
            if (response.isOk()) {
                String responseBody = response.body();
                System.out.println("API响应成功: " + responseBody);
                // 可进一步解析JSON响应: JSONObject respJson = JSONUtil.parseObj(responseBody);
            } else {
                System.err.println("请求失败! 状态码: " + response.getStatus()
                        + "\n错误信息: " + response.body());
            }
        } catch (Exception e) {
            System.err.println("请求异常: " + e.getMessage());
        }
    }
}
